﻿using ExitGames.Client.Photon;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using Common;

public class PhotonServerManager : MonoBehaviour, IPhotonPeerListener
{
    public static PhotonPeer peer;

    private Dictionary<OpCode, Request> requestDic = new Dictionary<OpCode, Request>();

    public static PhotonServerManager Instance {
        get;
        private set;
    }

    void Awake()
    {
        if (Instance == null)
        {
            Instance = this;
            DontDestroyOnLoad(this.gameObject);
        }
    }
    void Start()
    {
        peer = new PhotonPeer(this, ConnectionProtocol.Tcp);
        peer.Connect("127.0.0.1:4530", "StarWarServer");
    }

    // Update is called once per frame
    void Update()
    {
        peer.Service();  //什么状态下都要执行
    }

    public void DebugReturn(DebugLevel level, string message)
    {
        Debug.LogError(message);
    }

    public void OnOperationResponse(OperationResponse operationResponse)
    {
        OpCode opCode = (OpCode)operationResponse.OperationCode;

        Request request = GetDicValueTools.GetValue<OpCode, Request>(requestDic, opCode);

        request.OnOperationReponse(operationResponse);
    }

    public void OnStatusChanged(StatusCode statusCode)
    {
        switch (statusCode)
        {
            case StatusCode.Connect:
                Debug.Log("服务器已连接");
                break;
            case StatusCode.Disconnect:
                Debug.Log("服务器已断开");

                break;
        }
    }

    public void OnEvent(EventData eventData)
    {
        switch (eventData.Code)
        {
            case 1:
                Dictionary<byte, object> data = eventData.Parameters;
                object value;
                data.TryGetValue(1, out value);

                Debug.Log("服务器发来的事件 :" + value.ToString());
                break;
        }
    }

    public void AddRequest(Request request)
    {
        requestDic.Add(request.opCode, request);
    }

    public void RemoveRequest(Request request)
    { 
        requestDic.Remove(request.opCode);
    }
    void OnDestroy()
    {
        if (peer != null && peer.PeerState == PeerStateValue.Connecting)
        {
            peer.Disconnect();            //断开连接
        }
    }
}

public enum LoginCode
{ 
    failtrue = 0,
    success = 1
}